package com.rhaggarty.gaming.cardroom;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.rhaggarty.data.type.game.Card;

/**
 * A representation of a stateful deck or decks of cards.  This object has an immutable reference to a collection of ordered cards, as 
 * well as a representation of "where" in the shoe it is.  Finally it has a representation of where in the deck a requeue is necessary (i.e., a threshold
 * after which the shoe should be considered finished or in need of a wash/shuffle).  
 * 
 * Note that this class is not responsible for ordering/shuffling the cards. 
 * 
 * @author Ryan Haggarty (ryanmh@gmail.com)
 *
 *
 * TODO(rhaggarty): Extract THRESHOLD_RATIO to conf/injected property.
 */
public final class Shoe {

    private final List<Card> cards;
    
    private Iterator<Card> it;

    private static final float THRESHOLD_RATIO = .7f;

    private int currentPosition = 0;
    
    public Shoe(final int numDecks) {
        cards = new ArrayList<Card>(numDecks*Card.getCards().size());
        for (int i = 0; i < numDecks; i++) {
            cards.addAll(Card.getCards());
        }
        it = cards.iterator();
    }
    
    public List<Card> getCards() {
        return cards;
    }

    public void resetShoe() {
        it = cards.iterator();
    }
    
    public Card nextCard() throws ShoeFinishedException {
        if (it.hasNext()) {
            if (currentPosition++ / cards.size() > THRESHOLD_RATIO) {
                throw new ShoeFinishedException();
            }
            return it.next();
        }
        
        // only reachable if THRESHOLD_RATIO >= 1.0.
        throw new ShoeFinishedException();
    }
}
